package com.young.ums.service.impl;

import com.young.common.core.dal.service.IDataAccessService;
import com.young.common.exception.BaseException;
import com.young.common.util.CommonUtil;
import com.young.common.util.Page;
import com.young.common.util.StringUtils;
import com.young.ums.core.ETopic;
import com.young.ums.core.ISubscriber;
import com.young.ums.model.DeptUser;
import com.young.ums.service.IDeptUserService;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Resource;
import java.util.List;

/**
* 部门用户关联信息(N-N)服务实现
* Created by imrookie on 2018-9-30.
*/
@Service("deptUserService")
public class DeptUserServiceImpl implements IDeptUserService,ISubscriber {

    @Resource(name = "dataAccessService")
    IDataAccessService dataAccessService;//数据层服务

    private static final Logger logger = LoggerFactory.getLogger(DeptUserServiceImpl.class);

    private static final String MAPPER = "com.young.ums.mapper.deptUser";//mapper的namespace

    //获取数据列表
    @Override
    public List<DeptUser> getList(DeptUser obj) {
        return dataAccessService.getList(MAPPER + ".getList", obj);
    }

    //获取数据列表(分页)
    @Override
    public List<DeptUser> getPage(DeptUser obj, Page page) {
        return dataAccessService.getList(MAPPER + ".getList", obj, page);
    }

    //查询单条
    @Override
    public DeptUser get(String id) {
        return dataAccessService.getObject(MAPPER + ".get", id);
    }

    //统计数量
    @Override
    public int count(DeptUser obj) {
        return dataAccessService.getObject(MAPPER + ".count", obj);
    }

    //修改
    @Override
    public int update(DeptUser obj) {
        return dataAccessService.update(MAPPER + ".update", obj);
    }

    //批量删除
    @Override
    public int delete(String[] idArr) {
        int i = 0;
        for(String id : idArr){
            i += this.delete(id);
        }
        return i;
    }

    //删除单条
    @Override
    public int delete(String id) {
        return dataAccessService.delete(MAPPER + ".delete", id);
    }

    /**
     * 删除部门相关的关联关系
     *
     * @param deptId 部门id
     * @return
     */
    @Override
    public int deleteByDeptId(String deptId) {
        return dataAccessService.delete(MAPPER + ".deleteByDeptId", deptId);
    }

    /**
     * 删除用户相关的关联关系
     *
     * @param userId 用户id
     * @return
     */
    @Override
    public int deleteByUserId(String userId) {
        return dataAccessService.delete(MAPPER + ".deleteByUserId", userId);
    }

    //插入
    @Override
    public int insert(DeptUser obj) {
        if (StringUtils.isBlank(obj.getDeptId()) || StringUtils.isBlank(obj.getUserId())){
            throw new BaseException("部门编号和用户编号不允许为空");
        }
        if (StringUtils.isBlank(obj.getId())){
            obj.setId(CommonUtil.getUUID());
        }
        return dataAccessService.insert(MAPPER + ".insert", obj);
    }

    //批量插入
    @Override
    public int batchInsert(List<DeptUser> list) {
        int i = 0;
        for(DeptUser item : list){
            i += this.insert(item);
        }
        return i;
    }

    /**
     * 批量关联用户(N)到部门(1)
     *
     * @param deptId  部门id
     * @param userIds 用户id数组
     * @return
     */
    @Override
    public int relevanceUsers2Dept(String deptId, String[] userIds) {
        int i = 0;
        if (StringUtils.isNotBlank(deptId) && userIds != null && userIds.length > 0){
            for (String userId : userIds){
                //判断是否已经存在关联
                if (this.isRelevanced(deptId, userId)){
                    logger.info("[批量关联用户到部门] 部门[{}]与用户[{}]已经存在关联关系,跳过.", deptId, userId);
                    continue;
                }
                DeptUser deptUser = new DeptUser();
                deptUser.setDeptId(deptId);
                deptUser.setUserId(userId);
                i += this.insert(deptUser);//插入关联关系
            }
        }
        return i;
    }

    /**
     * 判断指定部门和用户是否已经关联
     *
     * @param deptId 部门id
     * @param userId 用户id
     * @return
     */
    @Override
    public boolean isRelevanced(String deptId, String userId) {
        DeptUser deptUser = new DeptUser();
        deptUser.setDeptId(deptId);
        deptUser.setUserId(userId);
        return this.count(deptUser) > 0;
    }

    /**
     * 返回订阅的主题数组
     */
    @Override
    public ETopic[] topics() {
        //订阅用户删除和部门删除主题
        return new ETopic[]{ETopic.DEPT_DEL, ETopic.USER_DEL};
    }

    /**
     * 消费
     *
     * @param topic   主题
     * @param message 传输对象
     */
    @Override
    public void consume(ETopic topic, Object message) {
        try{
            if (topic == ETopic.DEPT_DEL){
                this.deleteByDeptId(message.toString());
            }else if (topic == ETopic.USER_DEL){
                this.deleteByUserId(message.toString());
            }
        }catch (Exception e){
            logger.info("[UMS消息消费-DeptUserServiceImpl] 消费异常,主题={},消息={}", topic, message, e);
            throw new BaseException(e);
        }

    }
}